﻿
using Prism.Commands;
using Prism.Events;
using SoonCode.FocusTest.Events;
using SoonCode.FocusTest.Models;
using System.Windows.Input;
using System.Windows;
using Prism.Mvvm;
using SoonCode.FocusTest.Utils;
using Keyboard = System.Windows.Input.Keyboard;
using MessageBox = HandyControl.Controls.MessageBox;
using System.Windows.Threading;
using SoonCode.Core;

namespace SoonCode.FocusTest.ViewModels
{
    internal class TestItemDViewModel : BindableBase
    {
        private int TestItemIndex = 4;
        private RandomHelper randomHelper = new RandomHelper(0, 10);
        private int tabIndex = 0;
        private int currTime = 0;
        private DateTime startTime;
        private int err = 0;
        private string checkKey = "6";
        private string currNumber;
        private bool stop = false;
        private TestInfo testInfo;
        private IEventAggregator aggregator;
        private SubscriptionToken spacePressToken;
        private string numberList;
        private int numberIndex = 0;
        private DispatcherTimer timer;
        private Stack<Boolean> checkList = new Stack<Boolean>();
        private string helpSoundText = "停止播放提示语";
        private bool helpIsPlay = true;
        public string HelpSoundText
        {
            get { return helpSoundText; }
            set
            {
                helpSoundText = value;
                RaisePropertyChanged();
            }
        }

        public int Err
        {
            get { return err; }
            set
            {
                err = value;
                RaisePropertyChanged();
            }
        }
        public int CurrTime
        {
            get { return currTime; }
            set
            {
                currTime = value;
                RaisePropertyChanged();
            }
        }

        public TestItemDViewModel(IEventAggregator aggregator)
        {
            this.aggregator = aggregator;
            if (timer == null) timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.IsEnabled = false;
            timer.Tick += Timer_Tick; ; ;
            aggregator.GetEvent<EndTestEvent>().Subscribe(OnEndTest);
            aggregator.GetEvent<ChangeTestEvent>().Subscribe(OnChangeTest);
            this.aggregator.GetEvent<TestLoadEvent>().Subscribe(OnLoaded);

        }

        private void OnEndTest()
        {
            SoundPlayer.Stop();
            timer.Stop();
            stop = true;
        }
        private void OnChangeTest(int p)
        {
            timer.Stop();
            SoundPlayer.Stop();
            stop = true;
        }
        private void Timer_Tick(object? sender, EventArgs e)
        {
            CurrTime = (int)(DateTime.Now - startTime).TotalSeconds;
            if (currTime >= 300)
            {
                stop = true;
                SoundPlayer.PlayDing();
                timer.Stop();
                complate();
            }
        }

        private void OnLoaded(int p)
        {
            stop = true;
            if (p != this.TestItemIndex - 1) return;
            this.testInfo = GlobalModel.Instance.TestInfo;
            TabIndex = 0;
            Err = 0;
            CurrTime = 0;
            numberIndex = 0;
            checkList.Clear();
            stop = false;
            Task.Run(generateNumber);
            SoundPlayer.Play("1000:item4.mp3");

        }
        public int TabIndex
        {
            get { return tabIndex; }
            set
            {
                tabIndex = value;
                RaisePropertyChanged();
            }
        }
        public ICommand HelpCommand
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    if (helpIsPlay)
                    {
                        SoundPlayer.Stop();
                        HelpSoundText = "播放提示语";
                        helpIsPlay = false;
                    }
                    else
                    {
                        SoundPlayer.Play("item4.mp3");
                        HelpSoundText = "停止播放提示语";
                        helpIsPlay = true;
                    }
                });
            }
        }
        public ICommand SkipCommand
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    SoundPlayer.Stop();
                    this.aggregator.GetEvent<ChangeTestEvent>().Publish(TestItemIndex);
                });
            }
        }
        public ICommand StartCommand
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    spacePressToken = this.aggregator.GetEvent<SpaceKeyPressEvent>().Subscribe(OnSpaceKeyPress);
                    TabIndex = 1;
                    startTime = DateTime.Now;
                    currNumber = "";
                    SoundPlayer.Stop();
                    timer.Start();
                    Test();
                });
            }
        }

        public ICommand AnswerErrorCommand
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    stop = true;
                    timer.Stop();
                    SoundPlayer.Stop();
                    complate();
                });
            }
        }

        public void OnSpaceKeyPress()
        {
            if (currNumber == "") return;
            if (currNumber == checkKey)
            {
                checkList.Pop();
            }
            else
            {
                checkList.Push(false);
            }

            currNumber = "";
            Err = checkList.Count;
            if (Err >= 5)
            {
                stop = true;
                timer.Stop();
                SoundPlayer.Stop();
                complate();
            }
        }

        private async void generateNumber()
        {
            numberList = randomHelper.next(310, checkKey.ToInt());
        }

        private void complate()
        {
            this.aggregator.GetEvent<SpaceKeyPressEvent>().Unsubscribe(spacePressToken);
            var element = Keyboard.FocusedElement;
            Keyboard.Focus(null);
            DialogUtil.Show(aggregator,$"错误=（{Err}）位，时间=（{currTime}）秒，本项结束，进入下一项");
            Keyboard.Focus(element);
            testInfo.data[TestItemIndex - 1].item_score = (int)((double)currTime / 300 * 100) + "";
            this.aggregator.GetEvent<ChangeTestEvent>().Publish(TestItemIndex);
        }
        private async void Test()
        {
            await Task.Delay(1000);
            int interval = 0;
            bool appeared = false;
            while (CurrTime < 300)
            {
                if (stop) return;
                Err = checkList.Count;
                if (Err >= 5)
                {
                    break;
                }
                currNumber = numberList[numberIndex].ToString();
                if (currNumber == checkKey)
                    appeared = true;
                int i = CurrTime / 10;
                if (i > interval)
                {
                    interval = i;
                    if (!appeared)
                        currNumber = checkKey;
                }
                if (currNumber == checkKey)
                    checkList.Push(false);
                SoundPlayer.Play(currNumber + ".mp3");
                await Task.Delay(1500);
                numberIndex++;
            }

            currNumber = "";
            complate();
        }
    }
}
